<template>
  <div class="app-container">
    <Find :OriginalFilter="{ static: true }" @Launchform="Launchform3" :formList="formList" @findClicked="findData" />

    <el-card style="margin-top: 10px" shadow="always" :body-style="{ padding: '5px' }">
      <div style="display: flex">
        <div style="width: 70%">
          <h1 style="font-size: 17px">{{ $t(`Print.InstructionsAndMaterialsToBeArranged`) }}</h1>
          <Table
            @selectList="selectList"
            @currentRow="currentRowListOeder"
            :isLoading="isLoading"
            :selection="true"
            :tableHeader="tableHeader"
            :tableData="CyckeGenerationTableDate"
            :TableHeight="100"
          />
          <PageModule :PageData="{ total, buttonS: true }" @pageSizeChange="handleSizeChange" @pageChange="handleCurrentChange" />
        </div>
        <div style="margin-left: 15px; width: 25%">
          <h1 style="font-size: 17px">{{ $t(`Print.InstructionNumberDetails`) }}</h1>
          <Table
            :summaryData="summaryData"
            summary
            :isLoading="isLoading3"
            :tableHeader="tableHeader2"
            :tableData="QueryCommandNumberDetailsTableDate"
            :TableHeight="100"
          />
        </div>
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible1" width="80%" class="dialog pb0">
      <Find :OriginalFilter="{ static: true }" @Launchform="Launchform" :formList="formList1" @findClicked="findData1" />
      <div style="display: flex">
        <div style="margin-top: 20px; width: 70%">
          <Tables
            :functionList3="true"
            @selectList="selectList1"
            @currentRow="currentRowListOeder1"
            :isLoading="isLoading1"
            :selection="true"
            :tableHeader="tableHeader1"
            :tableData="CommandDataHasBeenArrangedTableDate"
            :TableHeight="100"
          />
        </div>

        <div style="margin-top: 20px; width: 30%; margin-left: 15px">
          <h1 style="font-size: 17px">{{ $t(`Print.InstructionNumberDetails`) }}</h1>
          <Table :isLoading="isLoading5" :tableHeader="tableHeader5" :tableData="QueryCommandNumberDetailsTableDate1" :TableHeight="30" />
          <h1 style="font-size: 17px; margin-top: 20px">{{ $t(`Print.BatchNumberDetails`) }}</h1>
          <Table :isLoading="isLoading6" :tableHeader="tableHeader6" :tableData="LotNumberDetailTableDate" :TableHeight="30" />
        </div>
      </div>

      <PageModule :PageData="{ total: total1, buttonS: true }" @pageSizeChange="handleSizeChange1" @pageChange="handleCurrentChange1" />
    </el-dialog>

    <el-dialog v-model="dialogVisible5" width="20%" class="dialog pb0">
      <div><span>{{ $t(`Print.BatchOrderOddNumberLimit`) }}:</span> <el-input-number v-model="GenerateABlankingBatchParms.maxQty" /></div>
      <div style="margin-top: 20px">
        <span>{{ $t(`Print.EvenNumberPerBatch`) }}:</span> <el-input-number v-model="GenerateABlankingBatchParms.lsQty" style="margin-left: 41px" />
      </div>
      <div style="margin-top: 20px">
        <span>{{ $t(`Print.MultiplierOfTheNumberOfOddNumbers`) }}:</span> <el-input-number v-model="GenerateABlankingBatchParms.sizeQty" style="margin-left: 14px" />
      </div>
      <div style="margin-top: 15px"><el-button type="primary" size="default" @click="GenerateABlankingBatchMethods">{{ $t(`Print.GenerateAPunchLot`) }}</el-button></div>
    </el-dialog>

    <el-dialog v-model="dialogVisible6" width="20%" class="dialog pb0">
      <div><span>{{ $t(`Print.BatchOrderOddNumberLimit`) }}:</span> <el-input-number v-model="GenerateABlankingBatchParms1.maxQty" /></div>
      <div style="margin-top: 20px">
        <span>{{ $t(`Print.EvenNumberPerBatch`) }}:</span> <el-input-number v-model="GenerateABlankingBatchParms1.lsQty" style="margin-left: 41px" />
      </div>
      <div style="margin-top: 20px">
        <span>{{ $t(`Print.MultiplierOfTheNumberOfOddNumbers`) }}:</span> <el-input-number v-model="GenerateABlankingBatchParms1.sizeQty" style="margin-left: 14px" />
      </div>
      <div style="margin-top: 15px"><el-button type="primary" size="default" @click="handleCloseMateriaLKlc as any">重新生成冲裁批次</el-button></div>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue'
import JMessage from '@/utils/JMessage'
export default defineComponent({
  name: 'CycleGeneration'
})
</script>
<script lang="ts" setup>
import { i18n, Jzhcn } from '@/i18n'
import {
  CyckeGeneration,
  CommandDataHasBeenArranged,
  QueryCommandNumberDetails,
  QueryCommandNumberDetails1,
  LotNumberDetail,
  GenerateABlankingBatch,
  GenerateABlankingBatch1
} from '@/api/AccountingDepartment/ProductionLabel/CycleGeneration'
import { ElMessage, ElMessageBox } from 'element-plus'

// 重新生成

// 生成指令批次
const GenerateABlankingBatchParms1 = ref<any>({
  lotNos: [],
  lsQty: 3000,
  maxQty: 4000,
  overRide: '',
  sizeQty: 200
})

const selectList1 = (row: any) => {
  GenerateABlankingBatchParms1.value.lotNos = row.map((item: any) => {
    return item.lotNo
  })
}

const handleCloseMateriaLKlc = (_done?: () => void) => {
  ElMessageBox.confirm('确定要重新生成冲裁批次吗?')
    .then(async () => {
      GenerateABlankingBatchParms1.value.overRide = true
      GenerateABlankingBatchMethods1()
    })
    .catch(() => {})
}

const dialogVisible6 = ref(false)

const GenerateABlankingBatchMethods1 = async () => {
  try {
    const result = await GenerateABlankingBatch1(GenerateABlankingBatchParms1.value)

    if (result.code === 200) {
      CommandDataHasBeenArrangedMethods()
      dialogVisible6.value = false
      JMessage.success(result.message)
    } else {
      JMessage.error(result.message)
    }
  } catch (error) {
    JMessage.error('生成异常请重试')
  }
}

// 生成指令批次
const GenerateABlankingBatchParms = ref<any>({
  lotNos: [],
  lsQty: 3000,
  maxQty: 4000,
  overRide: '',
  sizeQty: 200
})

const dialogVisible5 = ref(false)

const selectList = (row: any) => {
  GenerateABlankingBatchParms.value.lotNos = row.map((item: any) => {
    return item.lotNo
  })
}

const GenerateABlankingBatchMethods = async () => {
  try {
    const result = await GenerateABlankingBatch(GenerateABlankingBatchParms.value)

    if (result.code === 200) {
      CyckeGenerationMethdos()
      dialogVisible5.value = false
      JMessage.success(result.message)
    } else {
      JMessage.error(result.message)
    }
  } catch (error) {
    JMessage.error('生成异常请重试')
  }
}

// 批次号码明细
const LotNumberDetailTableDate = ref<any>([])

const isLoading6 = ref(false)

const LotNumberDetailMethods = async () => {
  isLoading6.value = true
  try {
    const result = await LotNumberDetail(QueryCommandNumberDetailsParms1.value.lotNo)

    // 用于存储最终表格数据
    const groupedData: any = {}

    // 遍历结果，将相同 lsNo 的项目分组
    result.forEach((item: any) => {
      if (!groupedData[item.lsNo]) {
        groupedData[item.lsNo] = {
          sizeNoL: item.lsNo,
          surplusQtyL: 0,
          sizes: []
        }
      }

      // 添加 sizeNo 和 qty 数据
      groupedData[item.lsNo].sizes.push({
        sizeNo: item.sizeNo,
        qty: item.qty
      })

      // 计算合计 qty
      groupedData[item.lsNo].surplusQtyL += item.qty
    })

    // 转换对象为数组
    LotNumberDetailTableDate.value = Object.values(groupedData)

    // 设置表头
    tableHeader6.value = [
      {
        label: '批次/号码',
        prop: 'sizeNoL'
      },
      {
        label: '合计',
        prop: 'surplusQtyL'
      }
    ]

    // 添加每个 sizeNo 的列头
    // 假设每个 lsNo 下面的 sizeNo 都是不同的
    result.forEach((item: any) => {
      if (!tableHeader6.value.find((header) => header.prop === item.sizeNo)) {
        tableHeader6.value.push({
          label: item.sizeNo,
          prop: item.sizeNo
        })
      }
    })

    // 在每个项中添加具体 sizeNo 的值
    LotNumberDetailTableDate.value.forEach((dataItem: any) => {
      dataItem.sizes.forEach((size: any) => {
        dataItem[size.sizeNo] = size.qty // 将 qty 赋值到对应的大小号
      })
    })

    isLoading6.value = false
  } catch (error) {
    JMessage.error('批次号码查询出错')
    isLoading6.value = false
  }
}

const QueryCommandNumberDetailsParms1 = ref({
  lotNo: ''
})

const currentRowListOeder1 = (row: any) => {
  QueryCommandNumberDetailsParms1.value.lotNo = row.lotNo
  QueryCommandNumberDetailsMethods1()
  LotNumberDetailMethods()
}

const QueryCommandNumberDetailsTableDate1 = ref<any>([])

const isLoading5 = ref(true)

const QueryCommandNumberDetailsMethods1 = async () => {
  isLoading5.value = true

  tableHeader5.value = tableHeader5.value.slice(0, 2)

  const result = await QueryCommandNumberDetails1(QueryCommandNumberDetailsParms1.value)

  const newObj: any = {}

  const sizeNoObj: any = {}

  let nulList: any = {}

  QueryCommandNumberDetailsTableDate1.value = result.codeDetails.map((item: any, index: number) => {
    item[item.sizeNo] = item.orderQty
    newObj[item.sizeNo] = item.orderQty
    sizeNoObj[item.sizeNo] = item.sizeNo

    newObj.sizeNoL = '订单数'

    sizeNoObj[item.sizeNo] = item.surplusQty

    sizeNoObj.sizeNoL = '预补数'

    nulList[item.sizeNo] = item.totalQty

    nulList.sizeNoL = '总数'
    return { ...item }
  })

  QueryCommandNumberDetailsTableDate1.value = [newObj, sizeNoObj, nulList]
  QueryCommandNumberDetailsTableDate1.value[0].surplusQtyL = result.codeDetailsSum.orderCount
  QueryCommandNumberDetailsTableDate1.value[1].surplusQtyL = result.codeDetailsSum.surplusCount

  nulList.surplusQtyL = 0

  for (let key in nulList) {
    if (!isNaN(parseFloat(key)) && isFinite(key as any)) {
      nulList.surplusQtyL += nulList[key]
    }
  }

  console.log(QueryCommandNumberDetailsTableDate1.value)

  if (QueryCommandNumberDetailsTableDate1.value.length !== 0) {
    QueryCommandNumberDetailsTableDate1.value.sizeNoL = '订单数'
    QueryCommandNumberDetailsTableDate1.value.sizeNoL = '预补数'
    QueryCommandNumberDetailsTableDate1.value.sizeNoL = '总数'
  }
  result.codeDetails.map((item: any, index: number) => {
    tableHeader5.value.push({
      label: item.sizeNo,
      prop: item.sizeNo
    })
  })
  isLoading5.value = false
}

// 明细号码
const QueryCommandNumberDetailsParms = ref({
  lotNo: ''
})

const summaryData = ref([
  {
    index: 1,
    num: 0
  },
  {
    index: 2,
    num: 0
  }
])

const currentRowListOeder = (row: any) => {
  QueryCommandNumberDetailsParms.value.lotNo = row.lotNo
  QueryCommandNumberDetailsMethods()
}

const isLoading3 = ref(true)

const QueryCommandNumberDetailsTableDate = ref([])

const QueryCommandNumberDetailsMethods = async () => {
  isLoading3.value = true
  try {
    const result = await QueryCommandNumberDetails(QueryCommandNumberDetailsParms.value)
    if (result.codeDetails.length !== 0) {
      QueryCommandNumberDetailsTableDate.value = result.codeDetails
      summaryData.value[0].num = result.codeDetailsSum.orderCount
      summaryData.value[1].num = result.codeDetailsSum.surplusCount
    } else {
      QueryCommandNumberDetailsTableDate.value = []
    }

    isLoading3.value = false
  } catch (error) {
    JMessage.error('指令号码明细查询出错')
    isLoading3.value = false
  }
}

// 已安排指令资料查询
const CommandDataHasBeenArrangedParms = ref({
  companyId: '',
  flag: '',
  lotNo: '',
  pageNum: 1,
  pageSize: 40,
  slipDateEnd: '',
  slipDateStart: '',
  style: ''
})

const clearFormList3 = () => {
  formList1.value.forEach((item) => {
    if (item.type === 'input') {
      item.inputValue = ''
    }
    if (item.type === 'select') {
      item.selectValue = ''
    }
  })
}

const Launchform = (row: any) => {
  CommandDataHasBeenArrangedParms.value.lotNo = row[0].inputValue
  CommandDataHasBeenArrangedParms.value.style = row[1].inputValue
  CommandDataHasBeenArrangedParms.value.flag = row[2].selectValue
  if (CyckeGenerationParms.value.flag === '所有') {
    CyckeGenerationParms.value.flag = ''
  } else if (CyckeGenerationParms.value.flag === '小于4000') {
    CyckeGenerationParms.value.flag = 'Y'
  } else if (CyckeGenerationParms.value.flag === '小于4000') {
    CyckeGenerationParms.value.flag = 'N'
  } else {
    CyckeGenerationParms.value.flag = ''
  }
  CommandDataHasBeenArrangedMethods()
}

const findData1 = (count: string) => {
  if (count === '置空') {
    clearFormList3()
  }
  if (count === '重新生成冲裁批次') {
    if (GenerateABlankingBatchParms1.value.lotNos.length === 0) {
      JMessage.warning('请勾选需要生成的指令')
    } else {
      dialogVisible6.value = true
    }
  }
}

const isLoading1 = ref(false)

const CommandDataHasBeenArrangedTableDate = ref([])

const CommandDataHasBeenArrangedMethods = async () => {
  isLoading1.value = true
  try {
    const result = await CommandDataHasBeenArranged(CommandDataHasBeenArrangedParms.value)
    CommandDataHasBeenArrangedTableDate.value = result.list
    if (result.list.length !== 0) {
      QueryCommandNumberDetailsParms1.value.lotNo = result.list[0].lotNo
      QueryCommandNumberDetailsMethods1()
      LotNumberDetailMethods()
    }
    total1.value = result.total
    isLoading1.value = false
  } catch (error) {
    JMessage.error('已安排指令资料查询出错')
    isLoading1.value = false
  }
}

const total1 = ref(0)

const handleSizeChange1 = (val: number) => {
  CommandDataHasBeenArrangedParms.value.pageSize = val
  CommandDataHasBeenArrangedMethods()
}

const handleCurrentChange1 = (val: number) => {
  CommandDataHasBeenArrangedParms.value.pageNum = val
  CommandDataHasBeenArrangedMethods()
}

const formList1 = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入指令',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入型体',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '订单数量',
    selectLabel: '',
    selectOptions: [
      {
        optionKey: '1',
        optionValue: '所有',
        optionLabel: '所有'
      },
      {
        optionKey: '2',
        optionValue: '小于4000',
        optionLabel: '小于4000'
      },
      {
        optionKey: '3',
        optionValue: '大于等于4000',
        optionLabel: '大于等于4000'
      }
    ]
  },
  {
    type: 'button',
    checkboxLabel: '重新生成冲裁批次'
  },
  {
    type: 'button',
    checkboxLabel: '置空',
    bgColor: '#1890FF'
  }
])

// 已安排指令
const dialogVisible1 = ref(false)

// 查询
const CyckeGenerationParms = ref({
  companyId: '',
  flag: '',
  lotNo: '',
  pageNum: 1,
  pageSize: 40,
  slipDateEnd: '',
  slipDateStart: '',
  style: ''
})

const findData = (count: string) => {
  if (count === '置空') {
    clearFormList5()
  }
  if (count === '已安排指令资料') {
    CommandDataHasBeenArrangedMethods()

    dialogVisible1.value = true
  }

  if (count === '生成冲裁批次') {
    GenerateABlankingBatchParms.value.overRide = false
    if (GenerateABlankingBatchParms.value.lotNos.length === 0) {
      JMessage.warning('请勾选需要生成的指令')
    } else {
      dialogVisible5.value = true
    }
  }
}

const clearFormList5 = () => {
  formList.value.forEach((item) => {
    if (item.type === 'input') {
      item.inputValue = ''
    }
    if (item.type === 'select') {
      item.selectValue = ''
    }
    if (item.type === 'date') {
      item.dateValue = ''
    }
  })
}

const Launchform3 = (row: any) => {
  CyckeGenerationParms.value.lotNo = row[0].inputValue
  CyckeGenerationParms.value.style = row[1].inputValue
  CyckeGenerationParms.value.flag = row[2].selectValue
  CyckeGenerationParms.value.slipDateStart = row[3].dateValue[0]
  CyckeGenerationParms.value.slipDateEnd = row[3].dateValue[1]

  if (CyckeGenerationParms.value.flag === '所有') {
    CyckeGenerationParms.value.flag = ''
  } else if (CyckeGenerationParms.value.flag === '小于4000') {
    CyckeGenerationParms.value.flag = 'Y'
  } else if (CyckeGenerationParms.value.flag === '小于4000') {
    CyckeGenerationParms.value.flag = 'N'
  } else {
    CyckeGenerationParms.value.flag = ''
  }

  CyckeGenerationMethdos()
}

const isLoading = ref(false)

const CyckeGenerationTableDate = ref([])

const CyckeGenerationMethdos = async () => {
  isLoading.value = true
  try {
    const result = await CyckeGeneration(CyckeGenerationParms.value)
    CyckeGenerationTableDate.value = result.list
    total.value = result.total
    if (result.list.length !== 0) {
      QueryCommandNumberDetailsParms.value.lotNo = result.list[0].lotNo
      QueryCommandNumberDetailsMethods()
    } else {
      QueryCommandNumberDetailsParms.value.lotNo = ''
      QueryCommandNumberDetailsMethods()
    }
    isLoading.value = false
  } catch (error) {
    JMessage.error('查询出错请重试')
    isLoading.value = false
  }
}

onMounted(() => {
  CyckeGenerationMethdos()
})

const total = ref(0)

const handleSizeChange = (val: number) => {
  CyckeGenerationParms.value.pageSize = val
  CyckeGenerationMethdos()
}

const handleCurrentChange = (val: number) => {
  CyckeGenerationParms.value.pageNum = val
  CyckeGenerationMethdos()
}

const formList = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入指令',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入型体',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '订单数量',
    selectLabel: '',
    selectOptions: [
      {
        optionKey: '1',
        optionValue: '所有',
        optionLabel: '所有'
      },
      {
        optionKey: '2',
        optionValue: '小于4000',
        optionLabel: '小于4000'
      },
      {
        optionKey: '3',
        optionValue: '大于等于4000',
        optionLabel: '大于等于4000'
      }
    ]
  },
  {
    type: 'date',
    dateLabel: '交期',
    dateValue: ''
  },
  {
    type: 'button',
    checkboxLabel: '置空',
    bgColor: '#1890FF'
  },
  {
    type: 'button',
    checkboxLabel: '已安排指令资料'
  },
  {
    type: 'button',
    checkboxLabel: '生成冲裁批次'
  }
])

const tableHeader = ref([
  {
    label: '指令号',
    prop: 'lotNo'
  },
  {
    label: '型体',
    prop: 'style'
  },
  {
    label: '颜色代码',
    prop: 'colorCode'
  },
  {
    label: '颜色',
    prop: 'color'
  },
  {
    label: '交期',
    prop: 'deliveryDate'
  },
  {
    label: '订单数',
    prop: 'orderQty'
  },
  {
    label: '预补数',
    prop: 'surplusQty'
  },
  {
    label: '订单总数',
    prop: 'totalQty'
  },
  {
    label: '审核状态',
    prop: 'checkFlag'
  }
])

const tableHeader1 = ref([
  {
    label: '指令号',
    prop: 'lotNo'
  },
  {
    label: '型体',
    prop: 'style'
  },
  {
    label: '颜色代码',
    prop: 'colorCode'
  },
  {
    label: '颜色',
    prop: 'color'
  },
  {
    label: '交期',
    prop: 'deliveryDate'
  },
  {
    label: '订单数',
    prop: 'orderQty'
  },
  {
    label: '预补数',
    prop: 'surplusQty'
  },
  {
    label: '订单总数',
    prop: 'totalQty'
  },
  {
    label: '审核状态',
    prop: 'checkFlag'
  }
])

const tableHeader2 = ref([
  {
    label: '号码',
    prop: 'sizeNo'
  },
  {
    label: '订单数',
    prop: 'orderQty'
  },
  {
    label: '预补数',
    prop: 'surplusQty'
  }
])

const tableHeader5 = ref<any>([
  {
    label: '号码',
    prop: 'sizeNoL'
  },
  {
    label: '合计',
    prop: 'surplusQtyL'
  }
])

const tableHeader6 = ref([
  {
    label: '批次/号码',
    prop: 'sizeNoL'
  },
  {
    label: '合计',
    prop: 'surplusQtyL'
  }
])
</script>

<style lang="less" scoped></style>
